const httpCodes = require("./http-codes");
const db = uniCloud.database();
const dbCmd = db.command;
const $ = dbCmd.aggregate;
const collection = db.collection("news-articles-image");
const limit = 10;

/**
 * 根据活动种类ID获取文章列表，并关联优惠券信息
 * @param {*} category_id 活动种类ID
 * @param {*} length 当前偏移量
 */
async function getArticlesAndCouponInfo(category_id, length = 0) {
  const res = await collection
    .aggregate()
    .match({ category_id, article_status: 1 })
    .lookup({
      from: "coupons",
      let: {
        images_coupon_id: "$coupon_id",
      },
      pipeline: $.pipeline()
        .match({
          _id: "$$images_coupon_id",
          status: dbCmd.neq(2),
        })
        .project({
          _id: 1,
          name: 1,
          discount: 1,
          validity: 1,
          customImage: 1,
          // 可选字段 status 可以省略，视前端需求而定
        })
        .skip(length)
        .limit(limit)
        .done(),
      as: "coupon_info",
    })
    .sort({
      last_modify_date: -1,
    })
    .end();

  return res;
}

/**
 * 获取文章总数（用于分页）
 */
async function getArticleCount(category_id) {
  const res = await collection
    .aggregate()
    .match({ category_id, article_status: 1 })
    .count("total")
    .end();
  return res.total || 0;
}

/**
 * 统一错误处理
 */
function handleError(error, operation) {
  console.error(`${operation}失败:`, error);

  const errorMessage =
    process.env.NODE_ENV === "development"
      ? `${operation}失败: ${error.stack}`
      : `${operation}失败`;

  return {
    code: httpCodes.INTERNAL_SERVER_ERROR,
    data: null,
    message: errorMessage,
  };
}

/**
 * 通用分页逻辑封装
 */
async function fetchArticlesWithPagination(category_id, length = 0) {
  if (!category_id) {
    return {
      code: httpCodes.BAD_REQUEST,
      data: null,
      message: "分类 ID 不能为空",
    };
  }

  try {
    const [res, total] = await Promise.all([
      getArticlesAndCouponInfo(category_id, length),
      getArticleCount(category_id),
    ]);

    const hasMore = length + res.data.length < total;

    return {
      code: httpCodes.SUCCESS,
      data: {
        list: res.data,
        count: total,
        hasMore,
      },
      message: "获取文章成功",
    };
  } catch (error) {
    return handleError(error, "获取文章");
  }
}

module.exports = {
  async getArticles(category_id) {
    return fetchArticlesWithPagination(category_id);
  },

  async loadMore(category_id, length) {
    return fetchArticlesWithPagination(category_id, length);
  },
};
